<template>
  <div class="content">
    <div class="contentBox">
<!--      TODO: 参考2.0搜索先注释掉 -->
      <div ref="topContent" style="display: none">
        <div class="formBox">
          <t-form
              v-show="!isFold"
              ref="form"
              :data="formData"
              :layout="'inline'"
              scroll-to-first-error="smooth"
              :class="isFold ? '' : 'paddingBottom'"
          >
            <t-form-item label="菜单名称" name="menuName" :label-width="58">
              <t-input placeholder="请输入菜单名称" v-model="formData.menuName"></t-input>
            </t-form-item>

            <t-form-item label="状态" name="status" :label-width="34">
              <t-select v-model="formData.status">
                <t-option key="apple" label="正常" value="apple" />
                <t-option key="banana" label="停用" value="banana" />
              </t-select>
            </t-form-item>

            <t-form-item class="formHandleBox" v-if="!isFold">
              <t-space size="small" style="gap: 10px;">
                <t-button class="queryBtn" @click="handleQuery">查询</t-button>
                <t-button class="resetBtn">重置</t-button>
                <span class="arrowCont">
                 <svg-icon
                     @click="handleArrow"
                     :name="'icon-arrowTD'"
                     class-name="arrowTD-svg-icon"
                     :style="isFold === true ? '' : 'transform: rotate(180deg)'"
                 ></svg-icon>
              </span>
              </t-space>
            </t-form-item>
          </t-form>
          <!--      展开-->
          <div class="upArrow" v-show="isFold">
            <svg-icon
                @click="handleArrow"
                :name="'icon-arrowTD'"
                class-name="arrowTD-svg-icon"
                :style="isFold === true ? '' : 'transform: rotate(180deg)'"
            ></svg-icon>
          </div>
        </div>
        <div class="line"></div>
      </div>
      <div class="tableBox">
        <div class="btnBox">
          <div class="left_b">
            <t-button class="hoverBlue" theme="primary" @click="handleDialog(true, {})" v-permission="['sys:menu:save']">
              <template #icon>
                <svg-icon
                    :name="'icon-add'"
                    class-name="add-svg-icon"
                ></svg-icon>
              </template>
              新增
            </t-button>

            <t-button theme="default" @click="handleExpandFold">
              <template #icon><SwapIcon style="transform: rotate(90deg)" /></template>
              展开/折叠
            </t-button>
          </div>
          <div class="right_r">
            <t-tooltip content="刷新">
              <t-button shape="circle" variant="outline" @click="refreshMenu">
                <RefreshIcon slot="icon" />
              </t-button>

            </t-tooltip>

          </div>
        </div>
        <div style="position: relative">
          <t-enhanced-table
              ref="tableRef"
              :height="tableHeight"
              v-model:expandedTreeNodes="expandedTreeNodes"
              row-key="id"
              drag-sort="row-handler"
              :data="tableState.tableData"
              :columns="tableState.columns"
              :tree="tableState.treeConfig"
              :expand-icon="expandIcon"
              :treeExpandAndFoldIcon="treeExpandIcon"
              lazy-load
              @expanded-tree-nodes-change="onExpandedTreeNodesChange"
          >
            <template #handle="{ row }">
                <div class="handleColumn">
                  <div class="item" @click="handleDialog(false, row)" v-permission="['sys:menu:update']">
                    <svg-icon
                        :name="'icon-itemEdit'"
                        class-name="item-svg-icon"
                    ></svg-icon>
                    <span>修改</span>
                  </div>

                  <div class="item" @click="handleDialog(true, row)" v-permission="['sys:menu:save']">
                    <svg-icon
                        :name="'icon-itemPlus'"
                        class-name="item-svg-icon"
                    ></svg-icon>
                    <span>新增</span>
                  </div>

                  <div class="item" @click="handleDel(row)" v-permission="['sys:menu:delete']">
                    <svg-icon
                        :name="'icon-itemDel'"
                        class-name="item-svg-icon"
                    ></svg-icon>
                    <span>删除</span>
                  </div>
                </div>
            </template>

            <template #icon="{ row }">
              <svg-icon
                  :name="row.icon"
                  class-name="menu-svg-icon"
              ></svg-icon>
            </template>
          </t-enhanced-table>

          <div class="emptyBox" v-if="tableState.tableData.length === 0">
            <svg-icon
                :name="'icon-emptyTable'"
                class-name="emptyTable-svg-icon"
            ></svg-icon>
            <span>暂无数据</span>
          </div>
        </div>
      </div>
    </div>

<!--    新增编辑菜单-->
    <MenuDialog
        :visibleDialog="visibleDialog"
        :dialogTitle="dialogTitle"
        :isNewItem="isNewItem"
        @closeDialog="closeDialog"
        :rowData="rowData"
    ></MenuDialog>
    <!--    删除弹窗-->
    <t-dialog
        v-model:visible="delVisible"
        class="dialogDel"
        theme="info"
        width="431"
        :header="delHeader"
        :on-confirm="onClickConfirm"
    />
  </div>
</template>

<script lang="jsx" setup>
import {computed, getCurrentInstance, nextTick, onMounted, onUnmounted, reactive, ref, watch} from "vue";
import {MessagePlugin} from "tdesign-vue-next";
import {debounce} from "../../utils/tools";
import {
  ChevronRightCircleIcon,
  ChevronDownCircleIcon,
  SwapIcon,
  RefreshIcon
} from 'tdesign-icons-vue-next';
import {
  menuList
} from '@/api/system/menu.js'
import MenuDialog from './components/menuDialog.vue'
import {delMenu, menuNav} from "../../api/system/menu";
import { useMenuList } from '@/pinia/menu.js'
import cache from '@/utils/cache.js'
import { useUserStore } from '@/pinia/user.js'
import { authInfo } from '@/api/login.js'

const pageInstance = getCurrentInstance()
// form 表单
const formData = reactive({
  menuName: '',
  status: ''
});
const onSubmit = ({ validateResult, firstError }) => {
  if (validateResult === true) {
    MessagePlugin.success('提交成功');
  } else {
    console.log('Validate Errors: ', firstError, validateResult);
    MessagePlugin.warning(firstError);
  }
};
let isFold = ref(false)
const handleArrow = () => {
  isFold.value = !isFold.value
}
const tableRef = ref(null);
//enhanced-table
const expandIcon = ref(false)

const expandedTreeNodes = ref([]);
const tableState = reactive({
  tableData: [],
  columns: [
    {
      colKey: 'menuName',
      title: '菜单名称',
      width: 260
    },
    {
      colKey: 'sort',
      title: '排序',
      ellipsis: true,
      width: 60
    },
    {
      colKey: 'icon',
      title: '图标',
      width: 180
    },
    {
      colKey: 'perms',
      title: '权限标识',
      ellipsis: true,
    },
    {
      colKey: 'component',
      title: '组件路径',
      ellipsis: true,
    },
    {
      colKey: 'createdAt',
      title: '创建时间',
      ellipsis: true,
      width: 170
    },
    {
      colKey: 'handle',
      title: '操作',
      align: 'center',
      width: 250
    }


  ],
  treeConfig: {
    childrenKey: 'children',
    treeNodeColumnIndex: 0,
    indent: 40,
    expandTreeNodeOnClick: false,
  }
})

const onExpandedTreeNodesChange = (expandedTreeNodes, context) => {
  console.log(expandedTreeNodes, context);
};
const treeExpandAndFoldIconRender = (h, { type, row }) => {
  return type === 'expand' ?  <ChevronRightCircleIcon /> : <ChevronDownCircleIcon />
};
const treeExpandIcon = computed(() => {
  // 自定义展开图标
  return treeExpandAndFoldIconRender;
})



// table 高度变化
const tableHeight = ref(0)
const getTableHeight = () => {
  nextTick(() => {
    const otherHeight = pageInstance.refs.topContent.offsetHeight
    const windowHeight = window.innerHeight
    tableHeight.value = windowHeight - otherHeight - 156
    console.log(tableHeight.value)
  })
}
watch(() => isFold.value, (newVal, oldVal) => {
  getTableHeight()
})

// window窗口 变化
const getWindowInfo = () => {
  const info = {
    width: window.innerWidth,
    height: window.innerHeight
  }
  console.log(info)
  getTableHeight()
}
const resizeInfo = debounce(getWindowInfo, 0)
onMounted(() => {
  getTableHeight()
  window.addEventListener('resize', resizeInfo);
  handleQuery()
})
onUnmounted(() => {
  window.removeEventListener('resize', resizeInfo);
})

// 查询
const handleQuery = () => {
  menuList(formData).then(res => {
    tableState.tableData = res.data
    console.log('menu list', res)
  })
}
// 展开、折叠
const expandAll = ref(false)
const handleExpandFold = () => {
  expandAll.value = !expandAll.value
  expandAll.value ? tableRef.value.expandAll() : tableRef.value.foldAll();
}

// 新增、编辑
const visibleDialog = ref(false)
const isNewItem = ref(false)
const dialogTitle = ref('')
const rowData = ref({})
// 新增打开弹窗
const handleDialog = (flag, row) => {
  rowData.value = row
  isNewItem.value = flag
  flag ? dialogTitle.value = '添加菜单' : dialogTitle.value = '修改菜单'
  visibleDialog.value = true
}
// 删除
const delVisible = ref(false)
const rowId = ref()
const delHeader = ref()
const handleDel = (row) => {
  delHeader.value = `是否确认删除名称为"${row.menuName}"的数据项？`
  delVisible.value = true
  rowId.value = row.id
}
const onClickConfirm = () => {
  delMenu(rowId.value).then(res => {
    if(res.code === 0) {
      delVisible.value = false
      MessagePlugin.success('删除成功！');
      handleQuery()
    }
  }).catch(error => {
    console.log(error)
  })
}
// 关闭弹窗
const closeDialog = (flag) => {
  visibleDialog.value = flag
  handleQuery()
}
const user = useUserStore()
// 刷新路由信息
const refreshMenu = async () => {
  // 获取路由数据
  const list = await menuNav()
  // 更新路由信息
  console.log('list list', list)
  useMenuList().$patch((state) => {
    state.asyncRoutes = list.data
  })

  useMenuList().updateRouteList(JSON.parse(JSON.stringify(list.data))).then(async _ => {
    window.location.reload()
  })
}
</script>

<style lang="scss" scoped>
.content {
  background-color: #EBECED !important;
  padding: 8px;
  .contentBox {
    overflow: hidden;
    position: relative;
    background-color: white;
    height: 100%;
    border-radius: 4px;

    .topBox {
      height: 65px;
      display: flex;
      padding: 20px 20px 17px 20px;
      background-color: rgba(255,255,255,1);
      .topLeft {
        font-size: 16px;
        font-weight: 600;
        color: rgba(51, 51, 51, 1);
      }
      .topRight {
        margin-left: auto;
        :deep(.t-button) {
          width: 77px;
          height: 28px;
          opacity: 1;
          border-radius: 3px;
          background: rgba(30, 117, 254, 1);
          border: 0.5px solid rgba(9.38399999999999, 95.71679999999998, 234.6, 1);
          padding: 0;
          font-size: 12px;
          font-weight: 400;
          color: rgba(255, 255, 255, 1);
        }
        .add-svg-icon {
          height: 16px;
          width: 16px;
          cursor: pointer;
          display: inline-block;
          vertical-align: middle;
          margin-right: 5px;
        }
      }
    }
    .line {
      height: 0;
      opacity: 1;
      background: rgba(204, 204, 204, 1);
      border: 1px solid rgba(239, 242, 245, 1);
      margin: 0 20px;
    }
    .formBox {
      padding: 0 20px;
      background-color: rgba(255,255,255,1);
      :deep(.t-form) {
        padding: 20px 0 20px 0;
        .t-form-inline {
          row-gap: 16px !important;
        }
        .t-form__item {
          width: 25%;
          height: 28px;
          margin-right: 0!important;
          padding-right: 10px;
          .t-range-input {
            height: 28px;
          }
          .t-form__label--right {
            text-align: left;
            padding-right: 0;
            font-size: 12px;
            font-weight: 400;
            color: rgba(0, 0, 0, 0.9);
          }
          .t-select__wrap {
            .t-input {
              height: 28px;
            }
          }
        }
        .t-form__item:nth-child(4) {
          padding-right: 0;
        }
        .t-form__item:nth-child(6) {
          .t-form__label--right {display: none}
          .t-form__controls {
            margin-left: 0 !important;
          }
          .t-space {
            width: 100%;
            .timeCheck {
              font-size: 12px;
              font-weight: 400;
              color: rgba(30, 117, 254, 1);
            }
          }
          .t-space-item:nth-child(1) {
            width: 126px;
          }
          .t-space-item:nth-child(2) {
            flex: 1;
          }
          .t-space-item:nth-child(3) {
            flex: 1;
          }
          .t-date-picker {
            height: 28px;
            width: 100%;
            .t-input {
              height: 28px;
            }
          }
          .timeType {
            float: left;
            width: 126px;
            text-align: left;
            height: 28px;
            line-height: 28px;
            span {
              margin-right: 10px;
              font-size: 12px;
              font-weight: 400;
              color: rgba(0, 0, 0, 0.9);
            }
            span:nth-child(4) {
              margin-right: 0;
            }
          }
        }
        .t-form__item:nth-child(7) {
          padding-right: 0;
        }
        .formHandleBox {
          margin-left: auto;
          text-align: right;
          padding-right: 0;
          .t-space {
            margin-left: auto;
            justify-content: center;
            align-items: center;
            .queryBtn {
              border: none;
              width: 56px;
              height: 30px;
              opacity: 1;
              border-radius: 3px;
              background: rgba(30, 117, 254, 1);
              font-size: 12px;
              font-weight: 400;
              color: rgba(255, 255, 255, 1);
              text-align: center;
            }
            .resetBtn {
              width: 56px;
              height: 30px;
              opacity: 1;
              border-radius: 3px;
              background: rgba(227, 238, 255, 1);
              border: 0.5px solid rgba(9.38399999999999, 95.71679999999998, 234.6, 1);
              font-size: 12px;
              font-weight: 400;
              color: rgba(30, 117, 254, 1);
              text-align: center;
            }
            .arrowCont {
              display: flex;
              justify-content: center;
              align-items: center;
              span {
                font-size: 12px;
                font-weight: 500;
                color: rgba(138, 138, 138, 1);
              }
              .arrowTD-svg-icon {
                height: 16px;
                width: 16px;
                cursor: pointer;
              }
            }
          }
          .t-form__controls {
            margin-left: 0 !important;
          }
        }
      }
      .upArrow {
        text-align: right;
        height: 20px;
        .arrowTD-svg-icon {
          height: 16px;
          width: 16px;
          cursor: pointer;
        }
      }
    }
    .tableBox {
      background-color: rgba(255, 255,255, 1);
      border-radius: 4px;
      .btnBox {
        //background-color: red;
        height: 50px;
        padding: 0 20px;
        display: flex;
        //justify-content: center;
        align-items: center;
        .left_b {
          :deep(.t-button--theme-primary) {
            width: 77px;
            height: 28px;
            opacity: 1;
            border-radius: 3px;
            background: rgba(30, 117, 254, 1);
            //border: 0.5px solid rgba(9.38399999999999, 95.71679999999998, 234.6, 1);
            padding: 0;
            font-size: 12px;
            font-weight: 400;
            color: rgba(255, 255, 255, 1);
            margin-right: 10px;
          }
          .add-svg-icon {
            height: 16px;
            width: 16px;
            cursor: pointer;
            display: inline-block;
            vertical-align: middle;
            margin-right: 5px;
          }
          :deep(.t-button--theme-default) {
            //width: 77px;
            height: 28px;
            opacity: 1;
            border-radius: 3px;
            font-size: 12px;
            font-weight: 400;
          }
        }
        .right_r {
          margin-left: auto;
        }
      }
      :deep(.t-table__header) {
        tr {
          th {
            padding: 7px 10px;
            box-sizing: border-box;
          }
          th:nth-child(1) {
            padding: 0 30px;
          }
        }

      }
      :deep(.t-table__body) {
        tr {
          td {
            padding: 6px 10px;
            box-sizing: border-box;
          }
          td:nth-child(1) {
            padding: 0 30px;
          }
        }
      }
      .exclMark-svg-icon {
        width: 12px;
        height: 12px;
        cursor: pointer;
      }
      .sort-svg-icon {
        width: 16px;
        height: 16px;
        cursor: pointer;
      }
      :deep(.custom-cell-select) {
        padding-right: 0!important;
      }
      :deep(.custom-cell-index) {
        padding-left: 0!important;
      }
      .handleColumn {
        display: flex;
        text-align: center;
        justify-content: center;
        align-items: center;
        .item {
          display: flex;
          justify-content: center;
          align-items: center;
          color: #1890ff;
          cursor: pointer;
          margin: 0 5px;
          .item-svg-icon {
            height: 16px;
            width: 16px;
          }
        }
      }
    }
    :deep(.t-table__empty) {
      display: none;
    }
    .emptyBox {
      position: absolute;
      height: 116px;
      width: 69px;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      text-align: center;
      .emptyTable-svg-icon {
        height: 62px;
        width: 69px;
      }
      span {
        font-size: 12px;
        font-weight: 400;
        color: rgba(92, 91, 91, 1);
      }
    }
  }
}
:deep(.dialogDel .t-dialog__wrap .t-dialog__position .t-dialog) {
  padding: 22px 22px 18px 22px;
  .t-icon.t-is-info {
    color: rgba(30, 117, 254, 1) ;
  }
  .t-dialog__body__icon {
    display: none;
  }
  .t-dialog__footer {
    padding-top: 31px;
    .t-dialog__cancel {
      background-color: white;
      border: none;
      width: 60px;
      height: 28px;
    }
    .t-dialog__confirm {
      width: 60px;
      height: 28px;
      opacity: 1;
      border-radius: 3px;
      background: rgba(30, 117, 254, 1);
    }
  }
}
.menu-svg-icon {
  height: 20px;
  width: 20px;
}
</style>
